﻿CREATE FUNCTION RATEx_(
	@IR float,@Term smallint,@FNP int,@ODF float
)RETURNS @T TABLE (APR float) AS
BEGIN

IF @IR > 1 SET @IR = @IR/100.0


DECLARE @PR float,@PRx float/*Periodic Rate*/SELECT @PR = 0,@PRx = .007
DECLARE @PFx float/*Payment Factor*/

WHILE @PR <> ROUND(@PRx,7) BEGIN
	SET @PR = ROUND(@PRx,7)
	SET @PFx = ((1.0-1.0/POWER((1+@PRx),@Term))/@PRx)*((POWER((1.0+@PRx),(1.0-@FNP)))/(1.0+(@PRx*@ODF)))
	SET @PRx = @PRx/1000
	--SELECT @PFx*@PMT PFx,@PRx PRx,ROUND(@PRx,5)*@PmtsPerYear APR,@APRx APRx,((1.0-1.0/POWER((1.0+@PRx),@Term))/@PRx) Pow
END

INSERT INTO @T VALUES(ROUND(@PRx,5))
RETURN
END
